package com.hsurosy.hsuchain.nft.base.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Http请求工具类
 *
 * @Author Hsu琛君珩
 * @Date 2024-10-04 18:51
 * @Description
 * @Version: v1.0.0
 */
public class HttpUtils {

    /**
     * 发送GET请求
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doGet(String host, String path, String method,
                                     Map<String, String> headers, Map<String, String> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * 发送POST表单请求
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @param bodys 请求体
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers, Map<String, String> querys,
                                      Map<String, String> bodys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * 发送POST请求（字符串形式）
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @param body 请求体
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers, Map<String, String> querys,
                                      String body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * 发送POST请求（字节数组形式）
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @param body 请求体
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doPost(String host, String path, String method,
                                      Map<String, String> headers, Map<String, String> querys,
                                      byte[] body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * 发送PUT请求（字符串形式）
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @param body 请求体
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers, Map<String, String> querys,
                                     String body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * 发送PUT请求（字节数组形式）
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @param body 请求体
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doPut(String host, String path, String method,
                                     Map<String, String> headers, Map<String, String> querys,
                                     byte[] body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * 发送DELETE请求
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param method 请求方法
     * @param headers 请求头信息
     * @param querys 查询参数
     * @return HttpResponse 响应对象
     * @throws Exception 异常
     */
    public static HttpResponse doDelete(String host, String path, String method,
                                        Map<String, String> headers, Map<String, String> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * 构建URL
     *
     * @param host 主机地址
     * @param path 请求路径
     * @param querys 查询参数
     * @return 构建的完整URL
     * @throws UnsupportedEncodingException 编码异常
     */
    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (sbQuery.length() > 0) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (sbQuery.length() > 0) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }

    /**
     * 包装HttpClient
     *
     * @param host 主机地址
     * @return HttpClient对象
     */
    private static HttpClient wrapClient(String host) {
        return HttpClientBuilder.create().build();
    }
}

